package red.mlz.gameservice.service.tag;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import red.mlz.common.entity.tag.Tag;
import red.mlz.common.utils.BaseUtils;
import red.mlz.gameservice.mapper.tag.TagMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TagService {

    @Resource
    private TagMapper tagMapper;

    @Transactional
    public List<Long> processTags(String tagsInput) {
        if (BaseUtils.isEmpty(tagsInput)) {
            return Collections.emptyList();
        }

        String[] tagNames = tagsInput.split(",");
        List<Long> tagIds = new ArrayList<>();


        for (String tagName : tagNames) {
            Tag existingTag = tagMapper.findByName(tagName.trim());
            if (existingTag != null) {
                tagIds.add(existingTag.getId());
            } else {
                Tag newTag = new Tag();
                newTag.setName(tagName.trim());
                newTag.setCreateTime(BaseUtils.currentSeconds());
                newTag.setUpdateTime(BaseUtils.currentSeconds());
                newTag.setIsDeleted(0);
                tagMapper.insert(newTag);
                tagIds.add(newTag.getId());
            }
        }

        return tagIds;
    }

    public Tag getById(Long tagId) {

        return tagMapper.getById(tagId);
    }

    public Tag extractById(Long tagId) {

        return tagMapper.extractById(tagId);
    }

    public Integer insert(Tag entity) {

        return tagMapper.insert(entity);
    }

    public Integer update(Tag entity) {

        return tagMapper.update(entity);
    }

    public Integer delete(Long id, Integer updateTime) {

        return tagMapper.delete(updateTime, id);
    }
}
